package sword_to_1;

import java.util.ArrayList;
import java.util.List;

public class LeeCode_36 {
    static class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    public static void main(String[] args) {
        Node x = treeToDoublyList(new Node(2, null, new Node(3)));
        System.out.println(x);
    }
    private static Node treeToDoublyList(Node root) {
        if (root == null)
            return null;
        List<Node> list = new ArrayList<>();
        dfs(list, root);
        if (list.size() == 1) {
            root.left = root;
            root.right = root;
            return root;
        }
        for (int i = 0; i < list.size(); i++) {
            if (i == 0){
                list.get(i).right = list.get(i + 1);
                list.get(i).left = list.get(list.size() - 1);
            }else if (i == list.size() - 1){
                list.get(i).left = list.get(i - 1);
                list.get(i).right = list.get(0);
            }else {
                list.get(i).left = list.get(i - 1);
                list.get(i).right = list.get(i + 1);
            }
        }
        return list.get(0);
    }
    private static void dfs(List<Node> list, Node node){
        if (node == null)
            return;
        dfs(list, node.left);
        list.add(node);
        dfs(list, node.right);
    }
}
